package com.amentretenimiento;

import java.net.URL;
import java.util.List;
import java.util.Vector;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class EsSupervisor extends ListActivity {
//	String urlamentretenimiento="http://201.155.80.190:8080/";
//	private String urlamentretenimiento="http://201.155.80.190:1863/";
	private String urlamentretenimiento=UsuariosSQLiteHelper.urlam;

//	String urlamentretenimiento="http://www.smartthinking.com.mx:8080/";


	Bundle extras;
	SAXParserFactory spf;
	SAXParser sp;
	XMLReader xr ;
	int ruta;
	LoginSitesList loginsitesList = null;
	private LayoutInflater mInflater;
	private Vector<RowData> data;
	String idAgente, passwrd;
	private String idcia;
	private String nombre;
	SharedPreferences preferences ;
	public SharedPreferences.Editor editor;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.essupervisor);
		
		
		Bundle extras=getIntent().getExtras();
		if(extras!=null){
			
//			String nombre=extras.getString("nombre");
			mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
	        data = new Vector<RowData>();
	        nombre=extras.getString("nombre");
			idAgente=extras.getString("idagente");
//			passwrd = extras.getString("pass");
			idcia=extras.getString("idCia");
			loginsitesList=mostrarInfor(idAgente);
//			Toast.makeText(getApplicationContext(), ""+loginsitesList.getidCliente().get(0).toString(), Toast.LENGTH_SHORT).show();

			if(loginsitesList.getidAgente().size()==0){
				
			     AlertDialog alertdialog=new AlertDialog.Builder(EsSupervisor.this).create();
								alertdialog.setIcon(R.drawable.icon);
						    	alertdialog.setTitle("Aviso");
						    	alertdialog.setMessage("No existen agentes asignados");
						    	alertdialog.setButton("Aceptar	", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface arg0, int arg1) {
										
										finish();
									}
								});
								alertdialog.show();
			}else{
			
					for (int i = 0; i < loginsitesList.getnombre().size(); i++) {
		
						RowData rd = new RowData(""+loginsitesList.getnombre().get(i),""+loginsitesList.getidAgente().get(i) );
				        data.add(rd);
					}
		
				CustomAdapter adapter = new CustomAdapter(this, R.layout.custom_row2,R.id.item, data);
				setListAdapter(adapter);
				}
			}
	}
	
	protected LoginSitesList mostrarInfor(String IdAgente) {
		LoginSitesList loginsitesList = null;
		
		try {
			
			SharedPreferences prefs =
				     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
			
			/** Handling XML */
			spf = SAXParserFactory.newInstance();
			sp = spf.newSAXParser();
			xr = sp.getXMLReader();

			/** Send URL to parse XML Tags */
			URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?Query=select%20*%20from%20agente%20where%20IdAgenteSupervisor="+prefs.getString("idagente", ""+0));
			
			Log.i("EsSupervisor", ""+sourceUrl);

			/** Create handler to handle XML Tags ( extends DefaultHandler ) */
			LoginMyXMLHandler myXMLHandler = new LoginMyXMLHandler();
			xr.setContentHandler(myXMLHandler);
			xr.parse(new InputSource(sourceUrl.openStream()));
			
		} catch (Exception e) {
			System.out.println("XML Pasing Excpetion = " + e);
		}
		loginsitesList = LoginMyXMLHandler.loginsitesList;
		
		return loginsitesList;
	}
	
	private class RowData {
	    protected String mItem;
	        protected String mDescription;

	        RowData(String item, String description){
	        mItem = item;
	        mDescription = description;             
	    }

	        @Override
	        public String toString() {
	                return mItem + " " +  mDescription;
	        }
	}
	
	private class CustomAdapter extends ArrayAdapter<RowData> {

        public CustomAdapter(Context context, int resource,
                        int textViewResourceId, List<RowData> objects) {
                super(context, resource, textViewResourceId, objects);

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder = null;

                //widgets displayed by each item in your list
                TextView item = null;
                TextView description = null;

                //data from your adapter
                RowData rowData= getItem(position);


                //we want to reuse already constructed row views...
                if(null == convertView){
                        convertView = mInflater.inflate(R.layout.custom_row2, null);
                        holder = new ViewHolder(convertView);
                        convertView.setTag(holder);
                }
                // 
                holder = (ViewHolder) convertView.getTag();
                item = holder.getItem();
                item.setText(rowData.mItem);
                item.setTextSize(18);
    			item.setTextColor(Color.BLACK);

                description = holder.getDescription();          
                description.setText(rowData.mDescription);
                description.setTextSize(16);
    			description.setTextColor(Color.BLACK);

                return convertView;
        }
	}
	
	@Override
	public void onBackPressed() {
		
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflate=getMenuInflater();
		inflate.inflate(R.menu.menupre, menu);
		return true;
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.salirpro:
			Intent salgo=new Intent(EsSupervisor.this, Login.class);
			startActivity(salgo);
			break;
		case R.id.agregar:
			Intent salgo2=new Intent(EsSupervisor.this, AgregarTienda2.class);
			salgo2.putExtra("idcia", idcia);
			salgo2.putExtra("idagente", idAgente);
			salgo2.putExtra("miusuario", nombre);

			startActivity(salgo2);
			break;
		}
		return false;
	}
	
	
	private class ViewHolder {      
	    private View mRow;
	    private TextView description = null;
	    private TextView item = null;

	        public ViewHolder(View row) {
	        mRow = row;
	        }

	        public TextView getDescription() {
	                if(null == description){
	                        description = (TextView) mRow.findViewById(R.id.item);
	                }
	                return description;
	        }

	        public TextView getItem() {
	                if(null == item){
	                        item = (TextView) mRow.findViewById(R.id.description);
	                }
	                return item;
	        }       
	}
	
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
	//	CustomAdapter adapter = (CustomAdapter) l.getAdapter();
		Bundle extras=getIntent().getExtras();
		if(extras!=null){
			SharedPreferences prefs =
				     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
	   	     
	   	     SharedPreferences.Editor editor=prefs.edit();
	   	        editor.putString("idpromotor", ""+loginsitesList.getidAgente().get(position).toString().trim());
	   	        editor.putString("nomagente", ""+loginsitesList.getnombre().get(position).toString().trim());

//	   	        editor.putString("idpromotor", ""+loginsitesList.getidAgente().get(position).toString().trim());

	   	        
	   	        editor.commit();
			
		//	Toast.makeText(getApplicationContext(), "el promotor es: "+loginsitesList.getnombre().get(position).toString(), Toast.LENGTH_LONG).show();
			
		
        Intent nd = new Intent(EsSupervisor.this, TiendaPromotor.class);
    	nd.putExtra("nombre", ""+loginsitesList.getnombre().get(position).toString());
		nd.putExtra("idagente", ""+loginsitesList.getidAgente().get(position).toString());
    	nd.putExtra("idcia", idcia);

        
        startActivity(nd);
	}
	
	
	}
}
